<?php
session_start();
require_once '../classes/Database.php';
require_once '../classes/ProductManager.php';
require_once '../classes/CDKManager.php';
require_once '../classes/SettingsHelper.php';

// 检查管理员登录
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$productManager = new ProductManager();
$cdkManager = new CDKManager();

// 获取参数
$productId = $_GET['product_id'] ?? null;
$status = $_GET['status'] ?? null;

        // 处理操作
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
            if ($_POST['action'] === 'delete_cdk') {
                $id = $_POST['id'] ?? 0;
                if ($cdkManager->deleteCDK($id)) {
                    $success = "CDK删除成功";
                } else {
                    $error = "CDK删除失败";
                }
            }
            
            if ($_POST['action'] === 'batch_delete') {
                $cdkIds = $_POST['cdk_ids'] ?? [];
                if (!empty($cdkIds)) {
                    $deleted = $cdkManager->batchDeleteCDK($cdkIds);
                    $success = "成功删除 {$deleted} 个CDK码";
                }
            }
            
            if ($_POST['action'] === 'import_cdks') {
                $productId = $_POST['product_id'] ?? 0;
                $cdkText = $_POST['cdk_text'] ?? '';
                
                if (!empty($cdkText) && $productId > 0) {
                    $cdkList = explode("\n", $cdkText);
                    $result = $cdkManager->importCDKs($cdkList, $productId);
                    $success = "成功导入 {$result['success']} 个CDK码";
                    if ($result['error'] > 0) {
                        $error = "导入失败 {$result['error']} 个CDK码";
                    }
                }
            }
            
            if ($_POST['action'] === 'generate_cdks') {
                $productId = $_POST['product_id'] ?? 0;
                $count = $_POST['count'] ?? 10;
                $length = $_POST['length'] ?? 16;
                
                if ($productId > 0 && $count > 0) {
                    $generatedCDKs = $cdkManager->batchGenerateCDK($count, $productId, $length);
                    $success = "成功生成 {$count} 个CDK码";
                    $generatedList = $generatedCDKs;
                }
            }
        }

// 获取CDK列表
$cdks = $cdkManager->getCDKsByProduct($productId, $status);
$products = $productManager->getAllProducts(false);
$statistics = $cdkManager->getCDKStatistics();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CDK管理 - <?php echo htmlspecialchars(getSiteName()); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/admin.css" rel="stylesheet">
    <style>
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 3px 15px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 25px rgba(0,0,0,0.15);
        }
        .stat-card.available {
            border-left-color: #28a745;
        }
        .stat-card.used {
            border-left-color: #17a2b8;
        }
        .stat-card.expired {
            border-left-color: #dc3545;
        }
        .stat-card.products {
            border-left-color: #ffc107;
        }
        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
            opacity: 0.8;
        }
        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stat-label {
            font-size: 1rem;
            color: #6c757d;
            font-weight: 500;
        }
        .stat-percentage {
            font-size: 0.9rem;
            margin-top: 5px;
            padding: 3px 8px;
            border-radius: 15px;
            display: inline-block;
        }
        .percentage-positive {
            background: #d4edda;
            color: #155724;
        }
        .percentage-negative {
            background: #f8d7da;
            color: #721c24;
        }
        .filter-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }
        .form-group {
            margin-bottom: 0;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏（移动端显示） -->
    <div class="top-navbar d-flex align-items-center justify-content-between">
        <button class="sidebar-toggle">
            <i class="fas fa-bars"></i>
        </button>
        <h5 class="mb-0">CDK管理 - <?php echo htmlspecialchars(getSiteName()); ?></h5>
        <div class="text-muted small">
            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($_SESSION['admin_username']); ?>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4 class="mb-3">
                <i class="fas fa-cogs me-2"></i><span><?php echo htmlspecialchars(getSiteName()); ?></span>
            </h4>
            <p class="text-muted mb-0 small">欢迎, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></p>
        </div>
        
        <nav class="nav flex-column">
            <a href="index.php" class="nav-link" data-tooltip="仪表盘">
                <i class="fas fa-tachometer-alt"></i><span>仪表盘</span>
            </a>
            <a href="products.php" class="nav-link" data-tooltip="商品管理">
                <i class="fas fa-box"></i><span>商品管理</span>
            </a>
            <a href="cdks.php" class="nav-link active" data-tooltip="CDK管理">
                <i class="fas fa-gift"></i><span>CDK管理</span>
            </a>
            <a href="orders.php" class="nav-link" data-tooltip="订单管理">
                <i class="fas fa-shopping-cart"></i><span>订单管理</span>
            </a>
            <a href="payments.php" class="nav-link" data-tooltip="支付记录">
                <i class="fas fa-credit-card"></i><span>支付记录</span>
            </a>
            <a href="settings.php" class="nav-link" data-tooltip="系统设置">
                <i class="fas fa-cog"></i><span>系统设置</span>
            </a>
            <a href="logout.php" class="nav-link" data-tooltip="退出登录">
                <i class="fas fa-sign-out-alt"></i><span>退出登录</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-gift me-2"></i>CDK管理
            </h2>
            <div class="text-muted">
                <i class="fas fa-calendar me-2"></i><?php echo date('Y年m月d日 H:i:s'); ?>
            </div>
        </div>
        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <!-- CDK统计信息 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon text-primary">
                    <i class="fas fa-key"></i>
                </div>
                <div class="stat-value"><?php echo $statistics['total_cdks']; ?></div>
                <div class="stat-label">总CDK数</div>
                <?php if ($statistics['total_cdks'] > 0): ?>
                <div class="stat-percentage percentage-positive">
                    <i class="fas fa-chart-line me-1"></i>总计
                </div>
                <?php endif; ?>
            </div>
            
            <div class="stat-card available">
                <div class="stat-icon text-success">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-value"><?php echo $statistics['available_cdks']; ?></div>
                <div class="stat-label">可用CDK</div>
                <?php if ($statistics['total_cdks'] > 0): 
                    $availablePercentage = round(($statistics['available_cdks'] / $statistics['total_cdks']) * 100, 1);
                ?>
                <div class="stat-percentage percentage-positive">
                    <i class="fas fa-percentage me-1"></i><?php echo $availablePercentage; ?>%
                </div>
                <?php endif; ?>
            </div>
            
            <div class="stat-card used">
                <div class="stat-icon text-info">
                    <i class="fas fa-shopping-cart"></i>
                </div>
                <div class="stat-value"><?php echo $statistics['used_cdks']; ?></div>
                <div class="stat-label">已使用CDK</div>
                <?php if ($statistics['total_cdks'] > 0): 
                    $usedPercentage = round(($statistics['used_cdks'] / $statistics['total_cdks']) * 100, 1);
                ?>
                <div class="stat-percentage <?php echo $usedPercentage > 50 ? 'percentage-positive' : 'percentage-negative'; ?>">
                    <i class="fas fa-percentage me-1"></i><?php echo $usedPercentage; ?>%
                </div>
                <?php endif; ?>
            </div>
            
            <div class="stat-card products">
                <div class="stat-icon text-warning">
                    <i class="fas fa-box"></i>
                </div>
                <div class="stat-value"><?php echo $statistics['product_count']; ?></div>
                <div class="stat-label">商品种类</div>
                <div class="stat-percentage percentage-positive">
                    <i class="fas fa-list me-1"></i>商品数
                </div>
            </div>
        </div>
        
        <!-- 批量生成CDK表单 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">
                    <i class="fas fa-plus-circle me-2"></i>批量生成CDK码
                </h3>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="generate_cdks">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>选择商品:</label>
                                <select name="product_id" class="form-control" required>
                                    <option value="">请选择商品</option>
                                    <?php foreach ($products as $product): ?>
                                    <option value="<?php echo $product['id']; ?>"><?php echo htmlspecialchars($product['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>生成数量:</label>
                                <input type="number" name="count" class="form-control" value="10" min="1" max="1000" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>CDK长度:</label>
                                <select name="length" class="form-control">
                                    <option value="12">12位</option>
                                    <option value="16" selected>16位</option>
                                    <option value="20">20位</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-magic me-2"></i>生成CDK码
                    </button>
                </form>
            </div>
        </div>
        
        <!-- 导入CDK表单 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">
                    <i class="fas fa-file-import me-2"></i>导入CDK码
                </h3>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="import_cdks">
                    <div class="form-group">
                        <label>选择商品:</label>
                        <select name="product_id" class="form-control" required>
                            <option value="">请选择商品</option>
                            <?php foreach ($products as $product): ?>
                            <option value="<?php echo $product['id']; ?>"><?php echo htmlspecialchars($product['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>CDK码列表 (每行一个):</label>
                        <textarea name="cdk_text" class="form-control" rows="5" placeholder="请输入CDK码，每行一个"></textarea>
                    </div>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-upload me-2"></i>导入CDK
                    </button>
                </form>
            </div>
        </div>
        
        <!-- 筛选表单 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">CDK筛选</h3>
            </div>
            <div class="card-body">
                <form method="GET" class="filter-form">
                    <div class="form-group">
                        <label>商品:</label>
                        <select name="product_id" class="form-control">
                            <option value="">所有商品</option>
                            <?php foreach ($products as $product): ?>
                            <option value="<?php echo $product['id']; ?>" <?php echo $productId == $product['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($product['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>状态:</label>
                        <select name="status" class="form-control">
                            <option value="">所有状态</option>
                            <option value="available" <?php echo $status == 'available' ? 'selected' : ''; ?>>可用</option>
                            <option value="used" <?php echo $status == 'used' ? 'selected' : ''; ?>>已使用</option>
                            <option value="expired" <?php echo $status == 'expired' ? 'selected' : ''; ?>>已过期</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn btn-primary">筛选</button>
                        <a href="cdks.php" class="btn">重置</a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- CDK列表 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">CDK列表</h3>
            </div>
            <div class="card-body">
                <form method="POST" id="batchForm">
                    <input type="hidden" name="action" value="batch_delete">
                    <table class="table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAll"></th>
                                <th>ID</th>
                                <th>CDK码</th>
                                <th>商品名称</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>使用时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cdks as $cdk): ?>
                            <tr>
                                <td><input type="checkbox" name="cdk_ids[]" value="<?php echo $cdk['id']; ?>"></td>
                                <td><?php echo $cdk['id']; ?></td>
                                <td><code><?php echo htmlspecialchars($cdk['cdk_code']); ?></code></td>
                                <td>
                                    <?php 
                                    $product = $productManager->getProductById($cdk['product_id']);
                                    echo $product ? htmlspecialchars($product['name']) : '未知商品';
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    $statusText = [
                                        'available' => '<span style="color: green;">可用</span>',
                                        'used' => '<span style="color: blue;">已使用</span>',
                                        'expired' => '<span style="color: red;">已过期</span>'
                                    ];
                                    echo $statusText[$cdk['status']] ?? $cdk['status'];
                                    ?>
                                </td>
                                <td><?php echo $cdk['created_at']; ?></td>
                                <td><?php echo $cdk['used_at'] ?: '-'; ?></td>
                                <td>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="delete_cdk">
                                        <input type="hidden" name="id" value="<?php echo $cdk['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('确定删除这个CDK吗？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <div style="margin-top: 15px;">
                        <button type="submit" class="btn btn-danger" onclick="return confirm('确定删除选中的CDK吗？')">批量删除</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        // 全选/取消全选
        document.getElementById('selectAll').addEventListener('change', function() {
            var checkboxes = document.querySelectorAll('input[name="cdk_ids[]"]');
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = document.getElementById('selectAll').checked;
            });
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/admin.js"></script>
</body>
</html>
